//
//  AuthenCompanyMarketPhtoFYVM.swift
//  kxf
//
//  Created by Elavatine on 2024/11/21.
//

import Foundation
import UIKit
import MCToast

class AuthenCompanyMarketPhtoFYVM: UIView {
    
    let selfHeight = AuthenPhotoVM().selfHeight*1+RegisterViewHeadTitleVM().selfHeight
    
    var imgSourceType = PHOTOTYPE.bankFront
    var imgType = ""
    var controller = WHBaseViewVC()
    
    var bankOcrFrontBlock:((NSDictionary)->())?
    
    
    override init(frame:CGRect){
        super.init(frame: CGRect.init(x: 0, y: frame.origin.y, width: SCREEN_WIDHT, height: selfHeight))
        self.backgroundColor = .white
        self.isUserInteractionEnabled = true
        //authen_photo_id_front
        initUI()
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var photoTitleVm : RegisterViewHeadTitleVM = {
        let vm = RegisterViewHeadTitleVM.init(frame: CGRect.init(x: 0, y: 0, width: 0, height: 0))
        vm.titleLabel.text = "银行卡信息"
        return vm
    }()
    lazy var bankCardPhotoVm : AuthenPhotoVM = {
        let vm = AuthenPhotoVM.init(frame: CGRect.init(x: SCREEN_WIDHT*0.25, y: self.photoTitleVm.frame.maxY, width: 0, height: 0  ))
        vm.titleLabel.text = "银行卡卡号照"
//        vm.isHidden = true
        vm.photoBlock = {()in
            self.imgSourceType = .bankFront
            self.imgType = "bankCardFront"
            self.takePickture()
        }
        vm.exampleBlock = {()in
            self.sampleAlertVm.showExampleImage(type: .bankFront)
        }
        return vm
    }()
    lazy var bankXuKePhotoVm : AuthenPhotoVM = {
        let vm = AuthenPhotoVM.init(frame: CGRect.init(x: SCREEN_WIDHT*0.25, y: self.photoTitleVm.frame.maxY, width: 0, height: 0  ))
        vm.titleLabel.text = "银行开户许可证照"
        vm.isHidden = true
        vm.photoBlock = {()in
            self.imgSourceType = .kaihuxuke
            self.imgType = "bankCardXuKe"
            self.takePickture()
        }
        vm.exampleBlock = {()in
            self.sampleAlertVm.showExampleImage(type: .kaihuxuke)
        }
        return vm
    }()
    lazy var bankZhuanZhangPhotoVm : AuthenPhotoVM = {
        let vm = AuthenPhotoVM.init(frame: CGRect.init(x: 0, y: self.bankCardPhotoVm.frame.maxY, width: 0, height: 0  ))
        vm.titleLabel.text = "转账功能开通申请书"
        vm.photoBlock = {()in
            self.imgSourceType = .zhuanzhangshenqing
            self.imgType = "bankCardZhuanZhang"
            self.takePickture()
        }
        return vm
    }()
    lazy var bankYiYuanPhotoVm : AuthenPhotoVM = {
        let vm = AuthenPhotoVM.init(frame: CGRect.init(x: SCREEN_WIDHT*0.5, y: self.bankCardPhotoVm.frame.maxY, width: 0, height: 0  ))
        vm.titleLabel.text = "开户意愿书以及其他"
        vm.photoBlock = {()in
            self.imgSourceType = .other
            self.imgType = "bankCardKaiHuYiYuan"
            self.takePickture()
        }
        return vm
    }()
    lazy var sampleAlertVm : AuthenPhotoSampleAlertVM = {
        let vm = AuthenPhotoSampleAlertVM.init(frame: .zero)
        vm.isHidden = true
        return vm
    }()
}

extension AuthenCompanyMarketPhtoFYVM{
    func initUI() {
        addSubview(photoTitleVm)
        addSubview(bankCardPhotoVm)
        addSubview(bankXuKePhotoVm)
        
        UIApplication.shared.keyWindow?.addSubview(sampleAlertVm)
//        addSubview(bankZhuanZhangPhotoVm)
//        addSubview(bankYiYuanPhotoVm)
        updateUIForFYPublic()
    }
    func updateUIForRefuse() {
        if AuthenCompanyMsgModel.shareInstance.settleWay == "UNINCORPORATE"{
            bankCardPhotoVm.setImgUrl(urlstring: "\(AuthenCompanyMsgModel.shareInstance.unincorporateBankCardImage)")
        }else{
            bankCardPhotoVm.setImgUrl(urlstring: "\(AuthenCompanyMsgModel.shareInstance.photoImgUrlBankCardFront)")
        }
        
        bankXuKePhotoVm.setImgUrl(urlstring: "\(AuthenCompanyMsgModel.shareInstance.photoImgUrlBankKaiHuXuKe)")
    }
    func setReadMode() {
        bankCardPhotoVm.setReadMode()
        bankXuKePhotoVm.setReadMode()
    }
    
    //MARK: 企业，富友通道，对私，法人结算的时候，需要传对公对私所有的信息
    func updateUIForFYPublic() {
        let bankCardPhotoVmCenter = bankCardPhotoVm.center
        //非法人结算，只需要银行卡卡号照片
        if AuthenCompanyMsgModel.shareInstance.settleWay == "UNINCORPORATE"{
            bankCardPhotoVm.center = CGPoint.init(x: SCREEN_WIDHT*0.5, y: bankCardPhotoVmCenter.y)
            bankXuKePhotoVm.center = CGPoint.init(x: SCREEN_WIDHT*0.5, y: bankCardPhotoVmCenter.y)
            if AuthenCompanyMsgModel.shareInstance.settleBankType == "2" || AuthenCompanyMsgModel.shareInstance.settleBankType == ""{
                bankCardPhotoVm.isHidden = false
                bankXuKePhotoVm.isHidden = true
            }else{
                bankCardPhotoVm.isHidden = true
                bankXuKePhotoVm.isHidden = false
            }
        }else{
            //法人结算
            //对私
            //富友通道，企业，对私，法人结算的时候，需要传对公对私所有的信息
            if AuthenCompanyMsgModel.shareInstance.settleBankType == "2" || AuthenCompanyMsgModel.shareInstance.settleBankType == ""{
                bankCardPhotoVm.center = CGPoint.init(x: SCREEN_WIDHT*0.25, y: bankCardPhotoVmCenter.y)
                bankCardPhotoVm.isHidden = false
                
                bankXuKePhotoVm.center = CGPoint.init(x: SCREEN_WIDHT*0.75, y: bankCardPhotoVmCenter.y)
                bankXuKePhotoVm.isHidden = false
                return
            }else{
                bankCardPhotoVm.isHidden = true
                bankXuKePhotoVm.isHidden = false
                bankXuKePhotoVm.center = CGPoint.init(x: SCREEN_WIDHT*0.5, y: bankCardPhotoVmCenter.y)
            }
        }
    }
}

extension AuthenCompanyMarketPhtoFYVM:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    @objc func takePickture(){
        let alertController=UIAlertController(title: "请选择照片来源", message: nil, preferredStyle: .actionSheet)

        let cancel=UIAlertAction(title:"取消", style: .cancel, handler: nil)
        
        let takingPictures=UIAlertAction(title:"拍照", style: .default){ action in
            if UIImagePickerController.isSourceTypeAvailable(.camera){
                if self.imgSourceType == .bankFront {
                    let vc = DXIDCardCameraController.init(type: DXIDCardType.bank)
                    vc.delegate = self
                    vc.modalPresentationStyle = .fullScreen
                    self.controller.present(vc, animated: true, completion: nil)
                }else{
                    let  cameraPicker = UIImagePickerController()
                    cameraPicker.delegate = self
                    cameraPicker.sourceType = .camera
                    //在需要的地方present出来
                    self.controller.present(cameraPicker, animated: true, completion: nil)
                }
            } else {
                print("不支持拍照")
            }
        }
        let photoPictures=UIAlertAction(title:"相册", style: .default){ action in
            if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
                let  cameraPicker = UIImagePickerController()
                cameraPicker.delegate = self
                cameraPicker.allowsEditing = true
                cameraPicker.sourceType = .photoLibrary
                //在需要的地方present出来
                self.controller.present(cameraPicker, animated: true, completion: nil)
            } else {
                print("不支持拍照")
            }
        }
        
        alertController.addAction(cancel)
        alertController.addAction(takingPictures)
        alertController.addAction(photoPictures)
        
        self.controller.present(alertController, animated:true, completion:nil)
    }
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        print("获得照片============= \(info)")
        self.controller.dismiss(animated: true, completion: nil)
        MCToast.mc_loading()
        let image = (info[UIImagePickerController.InfoKey.originalImage] as? UIImage)!
        let imageData = WHRequestTools.compressImage(toData: image)
//        let imageData = image.jpegData(compressionQuality: 1.0)
        
        DSImageUploader.shared.uploadImages(_image: imageData!,imgType: "\(self.imgType)") { text, value in
            DLLog(message: "\(text)")
            DLLog(message: "\(value)")
            MCToast.mc_remove()
            if value == true{
                if self.imgSourceType == .bankFront{
                    self.sendOcrBankCardRequest(urlString: "\(text)")
                }else if self.imgSourceType == .kaihuxuke{
                    self.bankXuKePhotoVm.setImgUrl(urlstring: "\(text)")
                    AuthenCompanyMsgModel.shareInstance.photoImgUrlBankKaiHuXuKe = "\(text)"
                }else if self.imgSourceType == .zhuanzhangshenqing{
                    self.bankZhuanZhangPhotoVm.setImgUrl(urlstring: "\(text)")
                    AuthenCompanyMsgModel.shareInstance.photoImgUrlBankZhuanZhang = "\(text)"
                }else if self.imgSourceType == .other{
                    self.bankYiYuanPhotoVm.setImgUrl(urlstring: "\(text)")
                    AuthenCompanyMsgModel.shareInstance.photoImgUrlBankOther = "\(text)"
                }
            }else{
                MCToast.mc_text("图片上传失败")
            }
        }
    }
}


extension AuthenCompanyMarketPhtoFYVM : DXIDCardCameraControllerProtocol {
    func cameraDidFinishShootWithCameraImage(image: UIImage) {
        let imageData = WHRequestTools.compressImage(toData: image)
//        let imageData = image.jpegData(compressionQuality: 1.0)
        MCToast.mc_loading()
        DSImageUploader.shared.uploadImages(_image: imageData!,imgType: "\(self.imgType)") { text, value in
            DLLog(message: "\(text)")
            DLLog(message: "\(value)")
            MCToast.mc_remove()
            if value == true{
                if self.imgSourceType == .bankFront{
                    self.sendOcrBankCardRequest(urlString: "\(text)")
                }else if self.imgSourceType == .kaihuxuke{
                    self.bankXuKePhotoVm.setImgUrl(urlstring: "\(text)")
                    AuthenCompanyMsgModel.shareInstance.photoImgUrlBankKaiHuXuKe = "\(text)"
                }else if self.imgSourceType == .zhuanzhangshenqing{
                    self.bankZhuanZhangPhotoVm.setImgUrl(urlstring: "\(text)")
                    AuthenCompanyMsgModel.shareInstance.photoImgUrlBankZhuanZhang = "\(text)"
                }else if self.imgSourceType == .other{
                    self.bankYiYuanPhotoVm.setImgUrl(urlstring: "\(text)")
                    AuthenCompanyMsgModel.shareInstance.photoImgUrlBankOther = "\(text)"
                }
            }else{
                MCToast.mc_text("图片上传失败")
            }
        }
    }
}
extension AuthenCompanyMarketPhtoFYVM{
    func sendOcrBankCardRequest(urlString:String) {
        MCToast.mc_loading()
        WHNetworkUtil.shareManager().GET(urlString: "\(URL_OCR_bank)?url=\(urlString)", vc: self.controller) { responseObject in
            DLLog(message: "\(responseObject)")
            if responseObject["code"]as? Int ?? 0 == 200{
                if self.bankOcrFrontBlock != nil{
                    let data = responseObject["data"]as? NSDictionary ?? [:]
                    let result = data["result"]as? NSDictionary ?? [:]
                    self.bankOcrFrontBlock!(result["result"]as? NSDictionary ?? [:])
                }
                
                self.bankCardPhotoVm.setImgUrl(urlstring: urlString)
                AuthenCompanyMsgModel.shareInstance.unincorporateBankCardImage = urlString
                AuthenCompanyMsgModel.shareInstance.photoImgUrlBankCardFront = urlString
            }else{
                self.controller.presentAlertVcNoAction(title: "\(responseObject["message"]as? String ?? "识别失败，请重新拍摄照片")", viewController: self.controller)
            }
        }
    }
}

